package com.thiswhyme.demo.msgpush.core.impl.nio;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * @description: 心跳处理器
 * @author: thiswhyme
 * @date: 2021/9/30
 */
public class HeartBeatHandler extends ChannelInboundHandlerAdapter {

    private static final int MAX_COUNT = 1;
    private int lossConnectCount = 0;

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent){
            IdleStateEvent event = (IdleStateEvent)evt;
            if (event.state()== IdleState.READER_IDLE){
                lossConnectCount ++;
                if (lossConnectCount > MAX_COUNT){
                    // TODO
                    ChannelManager.removeAndClose(ctx.channel());
                }
            }
        }else {
            super.userEventTriggered(ctx,evt);
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        lossConnectCount = 0;
    }
}
